import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { loadScript, randomString , messages } from "share/common";
import config from 'config'
import { Modal, Spin } from 'antd';
import locationImg from 'images/location.png'

const getLocationObject = location => {
  let locationValue = null;
  let hasLocation = false;
  if(location) {
    if(typeof location === 'string') {
      try {
        locationValue = JSON.parse(location);
      } catch(e) {}
    }
    else if(typeof location === 'object') {
      locationValue = location;
    }
    if(locationValue && typeof locationValue === 'object' && locationValue.latitude && locationValue.longitude) {
      hasLocation = true;
    }
  }
  return [hasLocation, locationValue];
};

class Map extends Component {

  state = {
    loading: false
  };

  map = null;
  marker = null;

  componentDidMount() {
    this.setState({ loading: true });
    Map.init()
      .then(() => {
        this.setState({ loading: false }, this.initMap);
      })
      .catch(e => {
        console.log(e);
      })
  }

  initMap = () => {
    const { getMap } = this.props;
    let container = ReactDOM.findDOMNode(this.ref);
    this.map = new AMap.Map(container, {
      zoom: 13
    });
    getMap && getMap(this.map);
    this.setLocation();
  };

  setLocation = () => {
    const { location } = this.props;
    let [hasLocation, locationValue] = getLocationObject(location);
    if(hasLocation) {
      const { latitude, longitude, address } = locationValue;
      let position = new AMap.LngLat(Number(longitude), Number(latitude));
      this.map.setCenter(position);
      this.marker = new AMap.Marker({
        position,
        title: address
      });
      this.map.add(this.marker);
    }
  };

  render() {
    const { className, style } = this.props;
    const { loading } = this.state;
    const wrapStyle = Object.assign({ width: '100%', height: '100%' }, style);
    return loading ? <Spin/> : <div className={className} style={wrapStyle} ref={ref => this.ref = ref}/>
  }

  static propTypes = {
    location: PropTypes.object.isRequired,
    className: PropTypes.string,
    style: PropTypes.object,
    getMap: PropTypes.func
  };

  static defaultProps = {
    className: '',
    style: {},
    location: {},
    getMap: () => {}
  };

}

Map.open = function(location) {
  Modal.info({
    title: location.address,
    content: <Map
      location={location}
      style={{
        width: '33.3vw',
        height: 300,
        marginLeft: -38
      }}
    />,
    width: 'calc(33.3vw + 64px)',
    iconType: "environment-o"
  });
};

Map.Text = function({ location, className = '', style = {} }) {
  let [hasLocation, locationValue] = getLocationObject(location);
  const wrapStyle = Object.assign({
    cursor: 'pointer',
    height: 18,
    width: 18
  }, style);
  let address = (locationValue && locationValue.address) || '-';
  return <div>
    {hasLocation && <img
      src={locationImg}
      className={className}
      style={wrapStyle}
      onClick={() => Map.open(locationValue)}
    />}
    {address}
    {!hasLocation && (
      <div style={{ color: '#7E97C5', fontSize: 14 }}>
        {messages('common-1.key80')/*该地址为手工填写，无法在地图上标注*/}
      </div>
    )}
  </div>
};

Map.init = function() {
  return new Promise((resolve, reject) => {
    if(window.AMap) {
      resolve();
    } else {
      let functionName = randomString(8);
      window[functionName] = function() {
        if(window[functionName]) {
          delete window[functionName];
        }
        resolve();
      };
      loadScript(`https://webapi.amap.com/maps?v=1.4.15&key=${config.aMapKey}&callback=${functionName}`)
        .then()
        .catch(e => {
          reject();
        })
    }
  })
};

export default Map;
